<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 头部搜索框区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="usersInfo.query"
            clearable
            @clear="getUsersInfo"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersInfo"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="userslist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽 -->
          <template v-slot="scoped">
            <el-switch
              v-model="scoped.row.mg_state"
              @change="sateChange(scoped.row)"
            ></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180px">
          <template v-slot="scoped">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showDialogVisible(scoped.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger "
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scoped.row.id)"
            ></el-button>

            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <!-- 分配角色 -->
              <el-button
                type="warning  "
                icon="el-icon-setting"
                size="mini"
                @click="assRoles(scoped.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="usersInfo.pagenum"
        :page-sizes="[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]"
        :page-size="usersInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框区域 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 表单区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框区域 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="emailClear"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="80px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
      </el-form>
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="80px"
      >
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
      </el-form>
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="80px"
      >
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo(editForm.id)"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 分配角色的对话框区域 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setdialogVisible"
      width="50%"
      @close="setRoleDialogClosed"
    >
      <div>
        <p>当前的用户：{{ userinfo.username }}</p>
        <p>当前的角色：{{ userinfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return cb()
      }
      // 返回一个错误提示
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      const regEmail = /^1[34578]\d{9}$/
      if (checkMobile.test(value)) {
        return cb()
      }
      // 返回一个错误提示
      cb(new Error('请输入正确的手机号'))
    }
    return {
      usersInfo: {
        query: '',
        pagenum: 1,
        pagesize: 3,
      },
      userslist: [],
      total: 0,
      addDialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '用户名在6~15个字符之间',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          //   { validator:checkEmail, message: '邮箱格式不正确，请重新输入', trigger: 'blur'}
          {
            pattern: /^\w+@\w+(\.\w+)+$/,
            message: '邮箱格式不正确，请重新输入',
            trigger: 'blur',
          },
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          //   { validator:checkMobile, message: '手机号码不正确，请重新输入', trigger: 'blur'}
          {
            pattern: /^1[34578]\d{9}$/,
            message: '手机号码不正确，请重新输入',
            trigger: 'blur',
          },
        ],
      },
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          //   { validator:checkEmail, message: '邮箱格式不正确，请重新输入', trigger: 'blur'}
          {
            pattern: /^\w+@\w+(\.\w+)+$/,
            message: '邮箱格式不正确，请重新输入',
            trigger: 'blur',
          },
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          //   { validator:checkMobile, message: '手机号码不正确，请重新输入', trigger: 'blur'}
          {
            pattern: /^1[34578]\d{9}$/,
            message: '手机号码不正确，请重新输入',
            trigger: 'blur',
          },
        ],
      },
      //控制分配角色对话框的显示隐藏
      setdialogVisible: false,
      //需要被分配用户的角色信息
      userinfo: {},
      //所有角色的数据列表
      rolesList: [],
      //已选中的角色id值
      selectedRoleId: '',
    }
  },
  created() {
    this.getUsersInfo()
  },
  mounted() {},
  methods: {
    async getUsersInfo() {
      const { data: res } = await this.$axios.get('users', {
        params: this.usersInfo,
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userslist = res.data.users
      this.total = res.data.total
      // console.log(res);
    },
    // 监测一页多少条数据
    handleSizeChange(newSize) {
      console.log(newSize)
      this.usersInfo.pagesize = newSize
      this.getUsersInfo()
    },
    // 监测页码
    handleCurrentChange(newCurrent) {
      console.log(newCurrent)
      this.usersInfo.pagenum = newCurrent
      this.getUsersInfo()
    },
    async sateChange(userInfo) {
      const { data: res } = await this.$axios.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      // console.log(res);
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    //关闭添加对话框的回调函数
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 完成添加用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        // console.log(valid);
        if (!valid) return this.$message.error('请填写完整用户信息')

        //请求接口
        const { data: res } = await this.$axios.post('users', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        // 关闭对话框
        this.addDialogVisible = false
        this.getUsersInfo()
      })
    },
    async showDialogVisible(id) {
      const { data: res } = await this.$axios.get('users/' + id)
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户失败')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    //修改用户关闭对话框
    emailClear() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户请求
    editUserInfo(id) {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        //发起请求
        const { data: res } = await this.$axios.put(
          'users/' + id,
          this.editForm
        )
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户失败！')
        }
        this.$message.success('更新用户成功！')
        this.getUsersInfo()
        this.editDialogVisible = false
      })
    },
    //删除用户
    async removeUserById(id) {
      // console.log(id);
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      console.log(confirmResult)
      //如果用户点击确认，则confirmResult 为'confirm'
      //如果用户点击取消, 则confirmResult获取的就是catch的错误消息'cancel'
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      // 调删除接口
      const { data: res } = await this.$axios.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败！')
      }
      this.$message.success('删除用户成功！')
      // console.log('删除成功');
      //优化小bug （当前页面只有一条数据时删除后 要跳转到上一页）
      if (this.total % this.usersInfo.pagesize === 1) {
        this.usersInfo.pagenum--
      }
      this.getUsersInfo()
    },
    //展开分配角色按钮
    async assRoles(userinfo) {
      this.userinfo = userinfo

      //在展开对话框之前渲染数据
      const { data: res } = await this.$axios.get('roles')
      if (res.meta.status !== 200)
        return this.$message.error('获取角色列表失败')
      this.rolesList = res.data

      this.setdialogVisible = true
    },

    //点击按钮，分配角色
    async saveRoleInfo() {
      if (!this.selectedRoleId) return this.$message.error('分配角色失败')

      //调接口

      const { data: res } = await this.$axios.put(
        `users/${this.usersInfo.id}/role`,
        { rid: this.selectedRoleId }
      )
      if (res.meta.status !== 200) return this.message.error('分配角色失败')
      this.$message.success('分配角色成功')
      this.getUsersInfo()
      this.setdialogVisible = false
    },
    //监听关闭对话框的事件
    setRoleDialogClosed() {
      this.selectedRoleId = ''
      this.userinfo = {}
    },
  },
}
</script>

<style scoped></style>
